package fr.toto.webui;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.kokotchy.betaSeriesAPI.model.Episode;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import fr.toto.files.AccesFile;
import fr.toto.menuitem.SetWatchedMenuItem;
import fr.toto.triseries.EpisodesSet;
import fr.toto.triseries.SeriesSet;
import fr.toto.constantes.Constantes;

public class MyHandler implements HttpHandler , Constantes {

	private static Pattern pat = Pattern
			.compile("(.*[^-]).S(\\d{1,2})E(\\d{2,3})");
	private String browse = "";
	private static List<String> rand = new ArrayList<String>();
	private Integer randomNumber;

	@Override
	public void handle(HttpExchange exchange) throws IOException {
		String requestMethod = exchange.getRequestMethod();
		if (requestMethod.equalsIgnoreCase("GET")) {
			Headers responseHeaders = exchange.getResponseHeaders();
			responseHeaders.set("Content-Type", "text/html");
			exchange.sendResponseHeaders(200, 0);

			OutputStream responseBody = exchange.getResponseBody();

			String s = entete();
			responseBody.write(s.getBytes());

			URI u = exchange.getRequestURI();

			browse = "";

			if (u != null) {
				String toto = u.getQuery();
				if (toto != null) {
					String[] values = toto.split("&");
					String[] number = values[0].split("=");
					if (number[0].equalsIgnoreCase(MESSAGES.getString("action0")) && rand.contains(number[1])) {
						rand.remove(number[1]);
						String[] action = values[1].split("=");
						if (action[0] != null && action[1] != null) {
							Episode ep = parseEpisode(action[1]);

							if (ep != null) {
								if (action[0].equalsIgnoreCase(MESSAGES.getString("action1"))) {
									Path file = AccesFile.Find(ep);
									if (file != null)
										AccesFile.Open(file);
									browse = "'" + ep.getShowUrl() + "','"
											+ ep.getNb() + "'";
								} else if (action[0].equalsIgnoreCase(MESSAGES.getString("action2"))) {
									new SetWatchedMenuItem(ep).doClick();
								}
							}
						}
					}
				}
			}
			
			Random randomGenerator = new Random();
			randomNumber = randomGenerator.nextInt(1000);
			rand.add(String.valueOf(randomNumber));

			String serie = "";
			for (Object ep : EpisodesSet.ListATraiter()) {
				if (ep instanceof Episode) {
					if (!serie.equalsIgnoreCase(((Episode) ep).getShowUrl())) {
						s = getSerieHTML((Episode) ep);
						if (!s.isEmpty()) {
							serie = ((Episode) ep).getShowUrl();
						}
						responseBody.write(s.getBytes());
					}
					s = getEpisodeHTML((Episode) ep);
					responseBody.write(s.getBytes());
				}
			}
			s = "</div></div>\n<script type=\"text/javascript\">afficheId("
					+ browse + ");</script>\n" + "</body>\n</html>";
			responseBody.write(s.getBytes());
			responseBody.close();
		}
	}

	private String entete() {
		return "<!DOCTYPE html>\n<html>\n<head>"
				+ "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"
				+ "<title> Episodes a voir</title>\n"
				+ "<meta name=\"Author\" content=\"T Robin\" />\n"
				+ "<style type=\"text/css\">"
				+ "img { width:90%; margin-left: 5%; margin-right: 5% }\n"
				+ ".serie  { text-align: center; margin:1%; border: 1px solid black; background-color: #C1E0FA; text-decoration:none; -webkit-border-radius: 20px; border-radius: 20px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; overflow: hidden; }\n"
				+ "h2 { margin:2px; }\n"
				+ "a { padding:0px; display:block; text-decoration:none; font-family:Lucida; color: #666666; }\n"
				+ ".episode { text-align: left; border-top: 1px dashed; background-color: #FFFFFF; }\n"
				+ ".episode:hover { color: #999999; background-color: #3B8DD0; }\n"
				+ ".detail { background-color: #FFFFFF;  padding: 1%;}\n"
				+ ".detail a { margin-left: 5%; margin-right: 5%; padding: 0px; border: 1px solid; width: 38%; display:inline-block; vertical-align:middle; background-color: #FAFAFA; text-align: center; -webkit-border-radius: 8px; border-radius: 8px; }\n"
				+ ".detail a:hover { color: #FFFFFF; background-color: #54709D; }\n"
				+ "</style>\n<script type=\"text/javascript\">\n"
				+ "function afficheId(serie,ep)  {\n"
				+ "  var  elem = document.getElementsByTagName('div');\n"
				+ "  for (var i = 0; i < elem.length; i++) {\n"
				+ "    if (elem[i].className == \"listepisode\" ) {\n"
				+ "      if (elem[i].id == serie) {\n"
				+ "        elem[i].style.visibility='visible';\n"
				+ "        elem[i].style.display='block';\n"
				+ "      }\n"
				+ "      else {\n"
				+ "        elem[i].style.visibility='hidden';\n"
				+ "        elem[i].style.display='none';\n"
				+ "      }\n"
				+ "    }\n"
				+ "    if( elem[i].className == \"detail\" ) {\n"
				+ "      if (elem[i].id == serie+ep) {\n"
				+ "        elem[i].style.visibility='visible';\n"
				+ "        elem[i].style.display='block';\n"
				+ "      }\n"
				+ "      else {\n"
				+ "        elem[i].style.visibility='hidden';\n"
				+ "        elem[i].style.display='none';\n"
				+ "      }\n"
				+ "    }\n"
				+ "  }\n"
				+ "}\n"
				+ "</script>\n</head>\n<div><div><img src=\"http://www.betaseries.com/membre/"
				+ settings.getLogin() + "/signature\">";
	}

	private String getSerieHTML(Episode ep) {
		String s = "";
		if (!ep.isSeen() && ep.isDownloaded()
				&& !SeriesSet.isArchived(ep.getShowUrl())) {
			s = "</div></div>\n";
			s += String
					.format("<div class=\"serie\"><a href=\"javascript:afficheId('%s','%s')\"><h2>%s</h2></a>",
							ep.getShowUrl(), ep.getNb(), ep.getShow());
			s += String.format("<div class=\"listepisode\" id=\"%s\">\n",
					ep.getShowUrl());
		}

		return s;
	}

	private String getEpisodeHTML(Episode ep) {
		String s = "";
		if (!ep.isSeen() && ep.isDownloaded()
				&& !SeriesSet.isArchived(ep.getShowUrl())) {

			if (browse.isEmpty()) {
				browse = "'" + ep.getShowUrl() + "','" + ep.getNb() + "'";
			}

			String id = ep.getShowUrl() + ep.getNb();

			String titre = String.format("%s - %02dx%02d", ep.getShow(),
					ep.getSeason(), ep.getEpisode());

			s = String.format(
					" <div class=\"episode\"><a href=\"javascript:afficheId('%s','%s')\">"
							+ "<strong>%s</strong><br />%s</a>\n", 
					ep.getShowUrl(), ep.getNb(), titre, ep.getTitle());

			s += String.format("<div class=\"detail\" id=\"%s\">", id);
			s += String.format("<a href=\"?%s=%d&%s=%s.%s\">%s</a>", MESSAGES.getString("action0"), randomNumber,
					MESSAGES.getString("action1"), ep.getShowUrl(), ep.getNb(), MESSAGES.getString("watchvideo"));
			s += String.format(
					"<a href=\"?%s=%d&%s=%s.%s\">%s</a></div>", MESSAGES.getString("action0"), randomNumber,
					MESSAGES.getString("action2"), ep.getShowUrl(), ep.getNb(), MESSAGES.getString("setwatched"));
			s += "</div>\n";

		}
		return s;
	}

	private Episode parseEpisode(String name) {

		Matcher m = pat.matcher(name);
		if (!m.matches())
			return null;
		String url = m.group(1).replace(".", " ").replace("_", " ").trim();
		int season = Integer.parseInt(m.group(2));
		int episode = Integer.parseInt(m.group(3));
		return EpisodesSet.find(url, season, episode);

	}

}
